package com.xxl.job.admin.controller;

import com.xxl.job.admin.core.model.XxlJobUser;
import com.xxl.job.admin.dto.UserVerificationRequest;
import com.xxl.job.admin.service.LoginService;
import com.xxl.job.admin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/verified")
public class AuthController {
    @Autowired
    private UserService userService;
    @PostMapping("/verify")
    public ResponseEntity<Map<String, Object>> verifyUser(@RequestBody UserVerificationRequest request, HttpServletRequest httpServletRequest) {
        Map<String, Object> response = new HashMap<>();

        // 从 session 中获取登录用户
        XxlJobUser User =  (XxlJobUser)httpServletRequest.getAttribute(LoginService.LOGIN_IDENTITY_KEY);
        String currentUser = User.getUsername();


        System.out.println("当前用户"+currentUser);


        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "当前用户信息获取失败，请重新登录");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }

        // 调用服务层验证逻辑
        System.out.println("准备调用验证svc");
        String verificationResult = userService.verifyUser(currentUser, request);

        if (verificationResult != null) {
            response.put("success", false);
            response.put("message", verificationResult);
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(response);
        }

        // 验证成功
        response.put("success", true);
        response.put("message", "身份验证成功");
        return ResponseEntity.ok(response);
    }

}
